from pyppeteer import launch
import asyncio
from lxml import etree
from tkinter import *
from tkinter import messagebox
from tkinter.ttk import *
import csv
import threading


#界面处理
root = Tk()
root.title("B站合集标题提取 —by路上很香")
root.geometry("450x450+500+300")
root.resizable(0,0)
root.iconbitmap("favicon.ico")


#全局变量
result = 0
links = 0
export_item = StringVar()


#组件定义
url_label = Label(root,text = "网站链接：")
url_entry = Entry(root,width = 30)
result_text = Text(root,width = 60)
begin_button = Button(root,text="读取",width = 5)
export_button = Button(root,text="提取",width = 5)
export_combobox = Combobox(root,textvariable=export_item,value=("导出链接","导出标题","导出全部"),state='readonly')
export_combobox.current(0)

async def getHtml(url):
    browser = await launch()
    page =  await browser.newPage()
    await page.goto(url)
    await page.waitForSelector(".part")
    html = await page.content()
    await browser.close()
    return html

def getResult(newurl):
    global result,links
    try:
        url = newurl
        html = asyncio.get_event_loop().run_until_complete(getHtml(url))
        html_tree = etree.HTML(html)
        result = html_tree.xpath("//span[@class='part']/text()")
        links = html_tree.xpath("//ul[@class='list-box']/li/a/@href")
    except Exception as e:
        messagebox.showerror("错误",e)
        return 0

def buttonCallback(event):
    try:
        global result,links
        url = url_entry.get()
        if url == "":
            thread = threading.Thread(target=messagebox.showinfo,args=("错误","url不能为空"))
            thread.start()
        else:
            getResult(url)
            if (result != []):
                result_text.delete(1.0,END);
                for i in range(len(result)):
                    links[i] = "https://www.bilibili.com" + links[i]
                    result_text.insert(END,result[i]+"\t"+links[i]+"\n")
            else:
                thread = threading.Thread(target=messagebox.showinfo,args=("错误","提取失败"))
                thread.start()
    except Exception as e:
        messagebox.showerror("错误",e)

def exportCallback(event):
    global result,links
    print(export_item.get())
    try:
        with open("result.csv","w+",encoding = "utf-8",newline = "") as f:
            writer = csv.writer(f)
            for i in range(len(result)):
                if export_item.get() == "导出链接":
                    writer.writerow([links[i]])
                elif export_item.get() == "导出标题":
                    writer.writerow([result[i]])
                else:
                    writer.writerow([result[i],links[i]])
            thread = threading.Thread(target=messagebox.showinfo,args=("信息","提取成功"))
            thread.start()
    except Exception as e:
        messagebox.showerror("错误",e)

#组件功能设计
url_label.place(x = 10,y = 20)
url_entry.place(x = 70,y = 20)
result_text.place(x = 10,y=115)
begin_button.place(x = 300,y = 15)
export_button.place(x = 300,y = 60)
export_combobox.place(x=90,y=60)
begin_button.bind("<Button-1>",buttonCallback)
export_button.bind("<Button-1>",exportCallback)

root.mainloop()






